package com.njuptB180316.boki.controller;

import com.njuptB180316.boki.dao.BookMapper;
import com.njuptB180316.boki.dataobject.Book;
import com.njuptB180316.boki.interceptor.NeedLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class IndexController {

    @Autowired
    private BookMapper bookMapper;

    /**
     * 分页式返回主界面
     */
    @NeedLogin
    @RequestMapping("/")
    public String index(ModelMap modelMap,
                        @RequestParam(name = "page",defaultValue = "1")Integer page,
                        @RequestParam(name = "size",defaultValue = "6")Integer size,
                        @RequestParam(name = "search",required = false)String search){
        int offset=size*(page-1);
        List<Book> books;
        int pages=1;
        if("".equals(search)||search==null){//如果不搜索
            books = bookMapper.selectByPagination(offset, size);
            pages = bookMapper.countRecords();//拿到所有图书数量
            if (pages%size!=0){
                pages = pages/size+1;
            }else{
                pages = pages/size;
            }
        }else{//按书名搜索
            books = bookMapper.searchByName(search);//获取搜索后的数据
        }
        modelMap.addAttribute("search", search);
        modelMap.addAttribute("books", books);
        modelMap.addAttribute("pages", pages);//页数
        return "index";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return "redirect:/";
    }
}
